<?php

class View
{

    /**
     * @var array
     */
    static protected $_paths = array(APP_PATH);

    /**
     * @var View
     */
    static protected $_instance = null;

    /**
     * i18n locale
     */
    public $l18n = null;

    /**
     * lock this method
     * constructor
     */
    private function __construct()
    {
        $this->l18n = Agis::getHelper('@l18n');

    }

    /**
     * a quiclier way single call to global helper
     * @return array
     */
    public function __call($name, $args)
    {
        return call_user_func_array(array(
            Agis::help($name),
            $name
        ), $args);
    }

    /**
     * better way to get helpers
     */
    public function __get($name)
    {
        return Agis::getHelper($name);
    }

    /**
     * @return View
     */
    static public function getInstance()
    {
        if (null == self::$_instance)
        {
            self::$_instance = new self;
        }
        return self::$_instance;

    }

    /**
     * find a path
     * @param string $script
     * @param bool $include
     * @param array $paths
     * @return string
     */
    static public function findScript($script, $use_include_path)
    {

        if (false == $use_include_path)
        {
            if (file_exists($script))
            {
                return $script;
            }
            return null;
        }

        foreach (self::$_paths as $path)
        {
            if (file_exists($path . '/' . $script))
            {
                return $path . '/' . $script;
            }
        }

        return null;
    }

    /**
     * escape string
     * @param string $string
     * @return string
     */
    static public function escape($string)
    {
        return htmlspecialchars($string, ENT_COMPAT, 'UTF8');
    }

    /**
     * process render
     * @param array
     */
    public function render($data, $script, $use_include_path = 1)
    {

        ob_start();

        $__file = self::findScript($script, $use_include_path);

        if (null == $__file)
        {
            throw new Exception("$script not found in view paths.");
        }

        extract($data, EXTR_SKIP);

        include $__file;

        return ob_get_clean();
    }

}
